
var isPause = 0;
const backgroundAudioManager = wx.getBackgroundAudioManager()
const updateManager = wx.getUpdateManager()
// var requestApi = require('/request/requestApi')
var isUpdateSongCount = 0; //是否已经记录收听过
var isNeedContinu = false;
var isNeedContinuSeek = 0;
var waitingErrorTimer = null;
var stopWaitingErrorStateTimer=false;
var isOnTimeUpdate = false;
var isConnectNetwork = false;
var waitingStateTimer = null;
var stopWaitingStateTimer = false;
var waitingStateCount = 0;
var waitingStateObjectForDuring = [];
// var waitingStateObjectForBuffered = [];
App({
    onLaunch: function () {

        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        })

        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })

        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
                title: '更新提示',
                content: '新版本下载失败',
                showCancel: false
            })
        })

    },

    onShow: function() {
        // Do something when show.
        console.log( '-----------------app.js 置于前台 -----------')
        this.globalData.appIsOnShow=true;
    },
    onHide: function() {
        // Do something when hide.
        console.log( '-----------------app.js 置于后台 -----------')
        this.globalData.appIsOnShow=false;
    },
    autoPlay: function (){
        var that = this;


        console.log('-------autoPlay----------',that.globalData.playList[that.globalData.playMusicIndex].mp3Title)
        this.playBackgroundAudioManager();
        // 处理 播放时间一直为0 则重新加载
        // that.onNoCurrentTimeControlMusic();
        this.initSetNormal();
        this.setWaitingTimerState('run');
        this.onWaittingControlSate();
        backgroundAudioManager.onPlay((res)=>{

            // that.onWaittingControlSate();
            console.log( 'backgroundAudioManager onPlay')
            that.globalData.isPlaying = true;
            // onError 如果错误 继续之前播放
            if (isNeedContinu==true){
                console.log( 'isNeedContinu  onError 如果错误 继续之前播放 ')
                // backgroundAudioManager.pause;
                //因 seek 会存在 虽然跳转完成但是实际没有跳转的问题,故循环调用
                that.onErrorControlMusic();
                // backgroundAudioManager.play;

            }
        })
        if (isOnTimeUpdate == false){
            isOnTimeUpdate = true;
            backgroundAudioManager.onTimeUpdate(()=>{
                if (that.globalData.appIsOnShow==false){
                    return;
                }
                //总时间
                var duration = Math.ceil(backgroundAudioManager.duration )

                //当前时间
                var currentTime = Math.ceil(backgroundAudioManager.currentTime )


                // ----异常处理------

                // 处理 播放时间一直未变化 则重新加载
                // that.onCurrentNoNextControlMusic();
                // that.onDownLoadErrorControlMusic();
                // 设置数据
                that.globalData.playMusicLength=duration;
                // if(isNeedContinu==true){
                //     that.globalData.playMusicCurrentLength=currentTime;
                // }
                that.globalData.playMusicCurrentLength=currentTime;
                that.globalData.isPause=false;
                that.globalData.isPlaying=true;
                //当收听超过3秒 并且此歌曲未记录过
                if (currentTime==Math.ceil(duration/2)&&isUpdateSongCount==0&&currentTime!=0){
                    isUpdateSongCount=1;
                    that.connectNetworkForGetNumber(1);
                }

                console.log('已下载'+backgroundAudioManager.buffered)
            })
        }

        backgroundAudioManager.onEnded(()=>{
            this.onEndedControlState();
        })
        backgroundAudioManager.onError(()=>{
            console.log('播放失败-----------');
            this.onErrorControlState();

        })
        backgroundAudioManager.onWaiting(()=>{
            console.log('等待下载中-----------');
            this.onErrorControlState();

        })
        backgroundAudioManager.onPause(()=>{
            console.log('已暂停-----------');

            this.globalData.isPause = false;
            this.setWaitingTimerState('stop')


        })
        backgroundAudioManager.onNext(()=>{
            isNeedContinu=false;
            console.log('app.js播放下一首-----------');
            // this.onErrorControlState();
            if (that.globalData.playPage=='index'){
                that.globalData.isNeedChangePro  = 1
            }
            if (that.globalData.playPage=='favor') {
                that.globalData.isNeedChangeFavorNext = 1;
            }

        })
        backgroundAudioManager.onPrev(()=>{
            isNeedContinu=false;
            console.log('app.js播放上一首-----------');
            // this.onErrorControlState();
            if (that.globalData.playPage=='index'){
                that.globalData.isNeedChangePro  = 1 ;
            }
            if (that.globalData.playPage=='favor') {
                that.globalData.isNeedChangeFavorPre = 1;
            }
        })
        //此方法 模拟器中不运行 手机中运行
        backgroundAudioManager.onSeeking(()=>{
            console.log('------------app.js 正在跳转-------------');
        })
        //此方法 模拟器中不运行 手机中运行
        backgroundAudioManager.onSeeked(()=>{
            console.log('------------app.js 跳转完成-------------');
        })


    },


    playBackgroundAudioManager:function (){
        var that = this;
        backgroundAudioManager.title =  that.globalData.playList[that.globalData.playMusicIndex].mp3Title;
        backgroundAudioManager.coverImgUrl = that.globalData.playList[that.globalData.playMusicIndex].mp3Image;
        backgroundAudioManager.src = that.globalData.playList[that.globalData.playMusicIndex].mp3Url;
        if (this.globalData.isPlaying==true){
            return;
        }
        backgroundAudioManager.play;
    },
    //sate 0 播放 1暂停 2终止
    musicControllerForState:function (state){
        var that = this
        isNeedContinu=false;
        isNeedContinuSeek=0;
        this.globalData.playMusicCurrentLength=0;
        // backgroundAudioManager.stop()
        isConnectNetwork=false;
        switch (state) {
            case 0:
                this.getMp3UrlFromNetwork();
                break;
        }
    },
    //sate 0 播放 1暂停 2终止
    musicControllerForPause:function (seek){
        var that = this
        var playMusicLength=Math.ceil(this.globalData.playMusicLength)
        isConnectNetwork=false;
        if (seek!=playMusicLength){
            isNeedContinu=true;
            isNeedContinuSeek=seek;
            this.getMp3UrlFromNetwork();
        }else{
            if (seek==0){
                seek=1;
            }
            this.onEndedControlState();
        }
        // backgroundAudioManager.stop()


    },
     getMp3UrlFromNetwork:function (){
        var that = this;
        // console.log('---------播放列表----------');
        // console.log(that.globalData.playList);
        // console.log('---------isConnectNetwork----------'+isConnectNetwork);
        if(isConnectNetwork==true){
            return;
        }
        // requestApi.kukeGetNextMusic(that.globalData.playList[that.globalData.playMusicIndex].l_code).then(res=>{
        //     that.globalData.playList[that.globalData.playMusicIndex].mp3Url=res.data.data;
        //     console.log(that.globalData.playList[that.globalData.playMusicIndex].mp3Url);
        //     console.log(that.globalData.playList[that.globalData.playMusicIndex].title);
        //     isUpdateSongCount=0;
        //     that.autoPlay()
        //     isConnectNetwork=false;
        // })isConnectNetwork=false;
        isConnectNetwork=true;
        console.log('-------------开始 获取mp3 播放地址-------------');
        wx.request({
            url: "https://dc.kuke.com/v2/music/track/play",
            method: 'GET',
            data: {
                lcode: that.globalData.playList[that.globalData.playMusicIndex].l_code,
                streamcode: '192'
            },
            success: function (res) {
                console.log('-------------结束 获取mp3 播放地址-------------');
                // console.log(res.data.data);
                that.globalData.playList[that.globalData.playMusicIndex].mp3Url=res.data.data;
                console.log(that.globalData.playList[that.globalData.playMusicIndex].mp3Url);
                console.log(that.globalData.playList[that.globalData.playMusicIndex].title);
                isUpdateSongCount=0;
                that.autoPlay()
                isConnectNetwork=false;
            },
            fail:function (res) {
                console.log('---------请求失败----------');
                // console.log(res)
                isConnectNetwork=false;
            }
        })
        this.connectNetworkForGetNumber(0);

    },
    connectNetworkForGetNumber:function (isGetOrSet) {
        if (isGetOrSet==1&&this.globalData.playPage=='favor'){
            return;
        }
        var that=this
        var data = that.globalData.playList[that.globalData.playMusicIndex];
        wx.request({
            url: that.globalData.kukeUrl+"/applet/playLog",
            method:'GET',
            data:{
                userId: that.globalData.userId ,
                workId:  data.workId,
                itemCode:  data.itemcode,
                lCode:  data.l_code,
                hasListened:  isGetOrSet,
            },
            success: function (res) {
                that.globalData.hasListened = res.data.data.workCount;
            }
        })
    },
    //--------------------- 播放特殊处理 ---------------------
    // onEnded 回调处理
    onEndedControlState:function(){
        var that = this
        that.globalData.playMusicCurrentLength=0;
        isNeedContinu=false;
        isNeedContinuSeek=0;
        if (that.globalData.playMusicIndex >= that.globalData.playList.length - 1) {
            that.globalData.playMusicIndex = 0;
            console.log('app.js播放结束 作品播放完成 ');
            that.globalData.isNeedChangePro=1;
            backgroundAudioManager.stop()
        }else{
            console.log('app.js播放下一曲');
            //播放下一曲
            that.globalData.playMusicIndex++;
            that.globalData.playMusicLength =0;
            backgroundAudioManager.stop()
            that.getMp3UrlFromNetwork();
        }
        that.globalData.isPlaying = false;
    },
    // onError 回调处理
    onErrorControlState:function(){
        var that = this
        isNeedContinuSeek = Math.ceil(backgroundAudioManager.currentTime )
        // isNeedContinuSeek = currentTime;
        isNeedContinu = true;
        console.log('appjs当前时间'+isNeedContinuSeek)
        this.setWaitingErrorState('stop');

        that.globalData.isPlaying = false;
        waitingErrorTimer = setInterval(function () {

            var isPause = backgroundAudioManager.paused;
            if (typeof isPause !='undefined'){
                that.setWaitingErrorState('stop');
                return;
            }
            that.getMp3UrlFromNetwork();
            // if (this.stopWaitingErrorStateTimer===false){
            //     setTimeout(that.onEndedControlState(),1000);
            // }
        },5000)
    },

    // onError 如果错误 继续之前播放
    //因 seek 会存在 虽然跳转完成但是实际没有跳转的问题,故循环调用
    onErrorControlMusic:function(){
        //当前时间
        var currentTime = Math.ceil(backgroundAudioManager.currentTime)

        console.log('因错误跳转到 '+isNeedContinuSeek)
        backgroundAudioManager.seek(Math.ceil(isNeedContinuSeek))
        this.globalData.playMusicCurrentLength=isNeedContinuSeek;
        if (currentTime>=isNeedContinuSeek){
            isNeedContinu=false;
            this.setWaitingErrorState('stop');
        }
    },

    onWaittingControlSate:function(){
        // if (waitingStateTimer!=null){
        //     return;
        // }
        var that= this
        waitingStateTimer = setInterval(function () {

            var currentTime = Math.ceil(backgroundAudioManager.currentTime);
            // var buffered = Math.ceil(backgroundAudioManager.buffered);

            waitingStateObjectForDuring.push(currentTime);
            // waitingStateObjectForBuffered.push(buffered);

            // console.log(waitingStateCount);
            console.log(waitingStateObjectForDuring);
            // console.log(waitingStateObjectForBuffered);

            if (waitingStateObjectForDuring.length%8==0){
                if(waitingStateObjectForDuring[0]==waitingStateObjectForDuring[7]){
                    // 播放时间一直为0 初始化加载失败
                    if (waitingStateObjectForDuring[0]==0||typeof waitingStateObjectForDuring[0] != 'undefined'){
                        console.log('播放时间一直为0 初始化加载失败 重新加载歌曲')
                        that.getMp3UrlFromNetwork();
                    }
                    // 播放时间一直为固定值 初始化加载失败
                    if (waitingStateObjectForDuring[0]>0 && typeof waitingStateObjectForDuring[0] != 'undefined'){
                        console.log('播放时间一直为固定值 初始化加载失败 重新加载歌曲并返回原位置')
                        that.onErrorControlState();
                    }
                    console.log('其他错误')
                    console.log(waitingStateObjectForDuring);
                    // console.log(waitingStateObjectForBuffered);
                }

                waitingStateObjectForDuring=[];
                // waitingStateObjectForBuffered=[];


            }

            // if (stopWaitingStateTimer==false){
            //     setTimeout(function () {
            //         that.onWaittingControlSate();
            //     },0)
            // }else{
            //     console.log('-----------关闭app.js  WaitingStateTimer---------')
            // }

        },1000)
    },
    initSetNormal:function(){
        waitingStateObjectForDuring=[];
        // waitingStateObjectForBuffered=[];
        this.setWaitingTimerState('stop');
        this.globalData.isPlaying=false;
    },
    //关闭或者开启 WaitingTimer state:run  || stop
    setWaitingTimerState:function(state){
        clearInterval(waitingStateTimer);
        if(state=='run'){

            stopWaitingStateTimer=false;
            waitingStateTimer=null;
        }else if (state=='stop') {

            stopWaitingStateTimer=true;
            waitingStateTimer=null;
        }
    },
    setWaitingErrorState:function(state){
        clearInterval(waitingErrorTimer);
        if(state=='run'){

            stopWaitingErrorStateTimer=false;
            waitingErrorTimer=null;
        }else if (state=='stop') {

            stopWaitingErrorStateTimer=true;
            waitingErrorTimer=null;
        }

    },
    globalData:{
        playType:0 , //0：数组 歌曲 1：二维数组 歌单 歌曲
        playPage:'index',//播放所属页面
        playPageProIndex:-1,
        playMusicIndex:0, //播放歌曲index
        playMusicLength:0, //歌曲总长度
        playMusicCurrentLength:0,
        playList:[], //播放歌单
        userId:1,
        isNeedChangePro:0, //是否需要切换了作品 0 1
        isNeedChangeFavorPre:0,
        isNeedChangeFavorNext:0,
        hasListened:0,
        kukeUrl:'https://applet.kuke.com/',
        indexNetworkData:{},
        indexSaveNetworkData:[],
        favorNetworkData:[],
        favorPlayStateForOrder:0 , // 0 顺序循环播放 1随机播放 2 单作品播放
        isPlaying:false,
        isPause:false,
        appIsOnShow:true,
        // kukeUrl:'http://59.110.14.41:30001/',
    }

})
